<template>
  <div class="show-main">
    <el-scrollbar style="height:100%">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline" size="small">
        <el-form-item label="">
          <el-select v-model="searchForm.school_id" placeholder="请选择学校" clearable>
            <el-option v-for="(item) in schoolList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click.stop="search">搜索</el-button>
          <el-button type="primary" @click.stop="reload">刷新</el-button>
          <el-button type="primary" @click.stop="add">添加</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="table" border size="small">
        <el-table-column prop="id" label="ID"></el-table-column>
        <el-table-column prop="name" label="宿舍楼名称"></el-table-column>
        <el-table-column prop="school_name" label="所属学校"></el-table-column>
        <el-table-column label="宿舍楼类型">
          <template slot-scope="scope">
            {{gender(scope.row.gender)}}
          </template>
        </el-table-column>
        <el-table-column prop="longitude" label="经度"></el-table-column>
        <el-table-column prop="latitude" label="纬度"></el-table-column>
        <el-table-column label="创建时间">
          <template slot-scope="scope">
            {{timeFormat(scope.row.create_time)}}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="edit(scope.row.id)">编辑</el-button>
            <el-button type="text" size="small" @click="del(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="page">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="searchForm.page" :page-sizes="[10,20,30,40]" :page-size="searchForm.limit"
          layout="total, sizes, prev, pager, next, jumper" :total="count">
        </el-pagination>
      </div>
      <el-dialog title="添加宿舍楼" :visible.sync="addVisible" width="700px" :before-close="handleClose('addForm')">
        <el-form ref="addForm" :model="addForm" label-width="100px" size="small" :rules="rules">
          <el-row>
            <el-col :span="12">
              <el-form-item label="宿舍楼名称" prop="name">
                <el-input v-model="addForm.name"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="宿舍楼类型" prop="gender">
                <el-select v-model="addForm.gender" placeholder="请选择宿舍楼类型">
                  <el-option label="男生宿舍楼" :value="0"></el-option>
                  <el-option label="女生宿舍楼" :value="1"></el-option>
                  <el-option label="混合宿舍楼" :value="2"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <div id="addMap" style="min-height: 400px;width: 100%;"></div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="20">
              <el-form-item label="详细地址">
                <el-input v-model="address" placeholder="请输入详细地址"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-button type="primary" @click="searchAdd('addForm')" size="small">搜索</el-button>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="宿舍楼经度" prop="longitude">
                <el-input v-model="addForm.longitude"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="宿舍楼纬度" prop="latitude">
                <el-input v-model="addForm.latitude"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="close('addVisible', 'addForm')" size="small">取 消</el-button>
          <el-button type="primary" @click="send('addVisible','addForm')" size="small">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog title="编辑宿舍楼" :visible.sync="editVisible" width="700px" :before-close="handleClose('editForm')">
        <el-form ref="editForm" :model="editForm" label-width="100px" size="small" :rules="rules">
          <el-row>
            <el-col :span="12">
              <el-form-item label="宿舍楼名称" prop="name">
                <el-input v-model="editForm.name"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="宿舍楼类型" prop="gender">
                <el-select v-model="editForm.gender" placeholder="请选择宿舍楼类型">
                  <el-option label="男生宿舍楼" :value="0"></el-option>
                  <el-option label="女生宿舍楼" :value="1"></el-option>
                  <el-option label="混合宿舍楼" :value="2"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <div id="editMap" style="min-height: 400px;width: 100%;"></div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="20">
              <el-form-item label="详细地址">
                <el-input v-model="address" placeholder="请输入详细地址"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-button type="primary" @click="searchAdd('editForm')" size="small">搜索</el-button>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="宿舍楼经度" prop="longitude">
                <el-input v-model="editForm.longitude"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="宿舍楼纬度" prop="latitude">
                <el-input v-model="editForm.latitude"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="close('editVisible', 'editForm')" size="small">取 消</el-button>
          <el-button type="primary" @click="send('editVisible','editForm')" size="small">确 定</el-button>
        </span>
      </el-dialog>
    </el-scrollbar>
  </div>
</template>
<script>
import { formatDate } from '@/untils/common.js'
import { getOwnSchool, storiedList, storiedFind, deleteStoried, StoriedInc, storiedEdit } from '@/network/api.js'

export default {
  name: 'dormitory',
  data () {
    return {
      searchForm: {
        page: 1,
        limit: 10,
        school_id: ''
      },
      count: 0, // 总记录数
      table: [],
      schoolList: [],
      addForm: {
        name: '', // 宿舍楼名称
        gender: 0, // 宿舍楼类型
        school_id: '', // 返现类型
        longitude: 104.04311, // 经度
        latitude: 30.64242 // 纬度
      }, // 添加的表单
      editForm: {
        id: 0,
        name: '', // 宿舍楼名称
        gender: '', // 宿舍楼类型
        school_id: '', // 返现类型
        longitude: '', // 经度
        latitude: '' // 纬度
      }, // 编辑的表单
      addVisible: false, // 添加表单
      editVisible: false, // 编辑表单
      rules: {
        name: [
          { required: true, message: '请输入宿舍楼名称', trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请选择宿舍楼类型', trigger: 'blur' }
        ],
        longitude: [
          { required: true, message: '缺少经度', trigger: 'blur' }
        ],
        latitude: [
          { required: true, message: '缺少纬度', trigger: 'blur' }
        ]
      },
      address: '',
      map: {}, // 地图
      markersArray: [] //
    }
  },
  created () {
    this.search()
  },
  computed: {
    gender () {
      return (gender) => {
        switch (gender) {
          case 0: return '男生宿舍'
          case 1: return '女生宿舍'
          case 2: return '混合宿舍'
        }
      }
    },
    timeFormat () {
      return (time) => {
        return formatDate(time)
      }
    }
  },
  methods: {
    reload () {
      location.reload()
    },
    async search () {
      try {
        const schoolRtn = await getOwnSchool({})
        this.schoolList = schoolRtn.data
        const rtn = await storiedList(this.searchForm)
        this.table = rtn.data.data
        this.count = rtn.data.count
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    // 每页条数变化
    handleSizeChange (val) {
      this.searchForm.limit = val
      this.search()
    },
    // 当前页变化
    handleCurrentChange (val) {
      this.searchForm.page = val
      this.search()
    },
    // 添加宿舍楼
    add () {
      this.addVisible = true
      this.$nextTick(() => {
        this.makeMap(parseFloat(this.addForm.latitude), parseFloat(this.addForm.longitude), 'addMap', 'addForm')
      })
    },
    // 创建地图
    makeMap (latitude, longitude, type, formName) {
      // 设置中心点
      const center = new window.qq.maps.LatLng(latitude, longitude)
      // 绘制地图
      this.map = new window.qq.maps.Map(document.getElementById(type), {
        center: center,
        zoom: 15
      })
      this.clearMarkers()
      const marker = new window.qq.maps.Marker({
        position: center,
        map: this.map
      })
      this.markersArray.push(marker)
      window.qq.maps.event.addDomListener(this.map, 'click', (event) => {
        this.clearMarkers()
        const marker = new window.qq.maps.Marker({
          position: event.latLng,
          map: this.map
        })
        this[formName].longitude = event.latLng.lng
        this[formName].latitude = event.latLng.lat
        this.markersArray.push(marker)
      })
    },
    clearMarkers () {
      if (this.markersArray) {
        for (const i in this.markersArray) {
          this.markersArray[i].setMap(null)
        }
        this.markersArray.length = 0
      }
    },
    // 搜索地址
    searchAdd (formName) {
      this.clearMarkers()
      window.geocoder = new window.qq.maps.Geocoder({
        complete: (result) => {
          this.map.setCenter(result.detail.location)
          this[formName].longitude = result.detail.location.lng
          this[formName].latitude = result.detail.location.lat
          const marker = new window.qq.maps.Marker({
            map: this.map,
            position: result.detail.location
          })
          this.markersArray.push(marker)
        }
      })
      window.geocoder.getLocation(this.address)
    },
    // 编辑宿舍楼
    async edit (id) {
      try {
        const rtn = await storiedFind({ id })
        this.editVisible = true
        this.$nextTick(() => {
          this.editForm = rtn.data
          this.makeMap(parseFloat(this.editForm.latitude), parseFloat(this.editForm.longitude), 'editMap', 'editForm')
        })
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    // 删除
    async del (id) {
      try {
        await deleteStoried({ id })
        this.search()
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    // 关闭弹出前操作(不包括取消按钮)
    handleClose (formName) {
      return (done) => {
        this.$refs[formName].resetFields()
        this.markersArray = []
        this.map = {}
        this.address = ''
        done()
      }
    },
    // 取消按钮
    close (visibleName, formName) {
      this.$refs[formName].resetFields()
      this[visibleName] = false
      this.markersArray = []
      this.map = {}
      this.address = ''
    },
    send (visibleName, formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          switch (formName) {
            case 'addForm': // 添加表单
              try {
                await StoriedInc(this.addForm)
                this.close('addVisible', 'addForm')
                this.search()
              } catch (e) {
                this.$message.error(e.message)
              }
              break
            case 'editForm': // 编辑表单
              try {
                await storiedEdit(this.editForm)
                this.close('editVisible', 'editForm')
                this.search()
              } catch (e) {
                this.$message.error(e.message)
              }
              break
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
</style>
